package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyZhongChengQuanLiuCheng;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeZhongChengQuanLiuCheng;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  V3中诚全流程CPS28
 *  @author 江小游
 */
@ApiPlan(productId = "169", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatZhongChengQuanLiuChengPhoneMd5 implements ApiPlatformPhoneMd5ConvertHandler {
    // key
    public static final String ENTER_KEY="8rqgrfnbmomdm51dw4qksv9hpg88hsmk";
    // 渠道号
    private static final String CORE="FIM2FW";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        //  撞库流程-默认JSON发送如果需要别的方式，或者需要增加请求头，请看apiDataChangeMessage实体拓展方法
        ApiPlatDataExchangeZhongChengQuanLiuCheng apiPlatDataExchange = new ApiPlatDataExchangeZhongChengQuanLiuCheng();
       ApiFieldConverter apiFieldConverter=ApiFieldConverter.create(apiDataExchangeParameter);
       // 渠道号
       apiPlatDataExchange.setChannel(CORE);
        //  手机号，小写
        apiPlatDataExchange.setMobileMd5(apiDataExchangeParameter.getPhoneMd5().toLowerCase());
        //  性别 1男，2女
        apiPlatDataExchange.setAge(apiFieldConverter.getAgeInt());
        Integer sex = ChooseEq.create(apiDataExchangeParameter.getSex())
                .when("0", 1)
                .when("1", 2)
                .end(1);
        apiPlatDataExchange.setGender(sex);
        // 用户名
        apiPlatDataExchange.setName("浩安星");
        apiPlatDataExchange.setCity(apiDataExchangeParameter.getCity());
        apiPlatDataExchange.setCityCode(apiPlatDataExchange.getCityCode());
        // 贷款金额   1->2万以内; 2->2-5万; 3->6-10万; 4->11-20万
        Integer loanAmount = ChooseEq.create(apiDataExchangeParameter.getLoanAmount())
                .when("1", 1)
                .when("2", 3)
                .when("3", 4)
                .end(1);
        apiPlatDataExchange.setAmount(loanAmount);
           //职业 1.上班族 2.自由职业 3.企业主（有营业执照）
        if (!ValidParam.isEmpty(apiDataExchangeParameter.getCareer())){
            Integer career = ChooseEq.create(apiDataExchangeParameter.getCareer())
                    .when("1", 1)
                    .when("2", 2)
                    .when("3", 3)
                    .when("4", 1)
                    .when("5", 3)
                    .end();
            apiPlatDataExchange.setVocation(career);
        }
         //本地社保 1->未交或已断; 2->连续未满六个月; 3->连续六个月以上
        if (!ValidParam.isEmpty(apiDataExchangeParameter.getSocialSecurity())){
            Integer socialSecurity = ChooseEq.create(apiDataExchangeParameter.getSocialSecurity())
                    .when("1", 1)
                    .when("2", 2)
                    .when("3", 3)
                    .when("4", 2)
                    .end();
            apiPlatDataExchange.setSocialInsurance(socialSecurity);
        }
          //本地公积金 1->未交或已断; 2->连续未满六个月; 3->连续六个月以上
        if (!ValidParam.isEmpty(apiDataExchangeParameter.getProvidentFund())){
            Integer providentFund = ChooseEq.create(apiDataExchangeParameter.getProvidentFund())
                    .when("1", 1)
                    .when("2", 2)
                    .when("3", 3)
                    .when("4", 2)
                    .end();
            apiPlatDataExchange.setAccumulationFund(providentFund);
        }
        // 本人房产 1->无; 2->有按揭房; 3->有全款房
        if (!ValidParam.isEmpty(apiDataExchangeParameter.getRealEstateInfo())){
            Integer realEstateInfo = ChooseEq.create(apiDataExchangeParameter.getRealEstateInfo())
                    .when("1", 1)
                    .when("2", 2)
                    .when("3", 2)
                    .when("4", 2)
                    .when("5", 2)
                    .when("6", 3)
                    .end();
            apiPlatDataExchange.setHouse(realEstateInfo);
        }
           // 本人车产 1->无; 2->有按揭车; 3->有全款车
        if (!ValidParam.isEmpty(apiDataExchangeParameter.getCarInfo())){
            Integer carInfo = ChooseEq.create(apiDataExchangeParameter.getCarInfo())
                    .when("1", 1)
                    .when("2", 3)
                    .when("3", 3)
                    .when("4", 3)
                    .end();
            apiPlatDataExchange.setCar(carInfo);
        }
        // 芝麻分 1->550以下; 2->550-600; 3->601-650; 4->651-700; 5->700以上;
        if (!ValidParam.isEmpty(apiDataExchangeParameter.getSesameCredit())){
            Integer sesameCredit = ChooseEq.create(apiDataExchangeParameter.getSesameCredit())
                    .when("1", 1)
                    .when("2", 3)
                    .when("3", 4)
                    .when("4", 5)
                    .end();
            apiPlatDataExchange.setSesame(sesameCredit);
        }
        // 花呗额度 1->无花呗; 2->5000以下; 3->5001-10000; 4->10001-20000; 5->20000以上
        if (!ValidParam.isEmpty(apiDataExchangeParameter.getHbLimit())){
            Integer hbLimit = ChooseEq.create(apiDataExchangeParameter.getHbLimit())
                    .when("1", 1)
                    .when("2", 2)
                    .when("3", 3)
                    .when("4", 4)
                    .when("5", 5)
                    .end();
            apiPlatDataExchange.setHuaBei(hbLimit);
        }
        //信用记录 1->信用良好无逾期; 2->近1年内网贷或信用卡逾期少于3次; 3->近1年内网贷或信用卡逾期超过3次
        if (!ValidParam.isEmpty(apiDataExchangeParameter.getOverdue())){
            Integer overdue = ChooseEq.create(apiDataExchangeParameter.getOverdue())
                    .when("1", 1)
                    .when("2", 3)
                    .when("3", 2)
                    .end();
            apiPlatDataExchange.setCreditRecord(overdue);
        }
        //  请求实体转换,默认JSON方式，如果FORM方式直接返回实体类，并且设置请求头为FORM表单
        // 1. 序列化对象为JSON字符串
        String rawJson = JsonUtils.toJson(apiPlatDataExchange);
        // 2. AES ECB加密
        AES aes = AES.createEcb(ENTER_KEY.getBytes());
        String encryptedBase64 = aes.encryptToBase64Str(rawJson);
        // 3. 构建Map并序列化
        Map<String, String> responseMap = new HashMap<>();
        responseMap.put("dataContent", encryptedBase64);
        return JsonUtils.toJson(responseMap);
    }


    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        //  进件流程-默认JSON发送如果需要别的方式，或者需要增加请求头，请看apiApplyMessage拓展方法
        ApiPlatApplyZhongChengQuanLiuCheng apiPlatApply = new ApiPlatApplyZhongChengQuanLiuCheng();
        // 渠道号
        apiPlatApply.setChannel(CORE);
        ApiFieldConverter apiFieldConverter=ApiFieldConverter.create(apiApplyParameter);
        // 撞库id
        apiPlatApply.setId(apiApplyParameter.dataExchangeApplyId());
        // 年龄
        apiPlatApply.setAge(apiFieldConverter.getAgeInt());
        //  手机号
        apiPlatApply.setMobile(apiApplyParameter.getPhone());
        //  性别 1男，2女
        Integer sex = ChooseEq.create(apiApplyParameter.getSex())
                .when("0", 1)
                .when("1", 2)
                .end(1);
        apiPlatApply.setGender(sex);
        // 用户名
        apiPlatApply.setName(apiApplyParameter.getUserName());
        apiPlatApply.setCity(apiApplyParameter.getCity());
        apiPlatApply.setCityCode(apiApplyParameter.getAreaCode());
        // 贷款金额   1->2万以内; 2->2-5万; 3->6-10万; 4->11-20万
        Integer loanAmount = ChooseEq.create(apiApplyParameter.getLoanAmount())
                .when("1", 1)
                .when("2", 3)
                .when("3", 4)
                .end(1);
        apiPlatApply.setAmount(loanAmount);
        //职业 1.上班族 2.自由职业 3.企业主（有营业执照）
        if (!ValidParam.isEmpty(apiApplyParameter.getCareer())){
            Integer career = ChooseEq.create(apiApplyParameter.getCareer())
                    .when("1", 1)
                    .when("2", 2)
                    .when("3", 3)
                    .when("4", 1)
                    .when("5", 3)
                    .end();
            apiPlatApply.setVocation(career);
        }
        //本地社保 1->未交或已断; 2->连续未满六个月; 3->连续六个月以上
        if (!ValidParam.isEmpty(apiApplyParameter.getSocialSecurity())){
            Integer socialSecurity = ChooseEq.create(apiApplyParameter.getSocialSecurity())
                    .when("1", 1)
                    .when("2", 2)
                    .when("3", 3)
                    .when("4", 2)
                    .end();
            apiPlatApply.setSocialInsurance(socialSecurity);
        }
        //本地公积金 1->未交或已断; 2->连续未满六个月; 3->连续六个月以上
        if (!ValidParam.isEmpty(apiApplyParameter.getProvidentFund())){
            Integer providentFund = ChooseEq.create(apiApplyParameter.getProvidentFund())
                    .when("1", 1)
                    .when("2", 2)
                    .when("3", 3)
                    .when("4", 2)
                    .end();
            apiPlatApply.setAccumulationFund(providentFund);
        }
        // 本人房产 1->无; 2->有按揭房; 3->有全款房
        if (!ValidParam.isEmpty(apiApplyParameter.getRealEstateInfo())){
            Integer realEstateInfo = ChooseEq.create(apiApplyParameter.getRealEstateInfo())
                    .when("1", 1)
                    .when("2", 2)
                    .when("3", 2)
                    .when("4", 2)
                    .when("5", 2)
                    .when("6", 3)
                    .end();
            apiPlatApply.setHouse(realEstateInfo);
        }
        // 本人车产 1->无; 2->有按揭车; 3->有全款车
        if (!ValidParam.isEmpty(apiApplyParameter.getCarInfo())){
            Integer carInfo = ChooseEq.create(apiApplyParameter.getCarInfo())
                    .when("1", 1)
                    .when("2", 3)
                    .when("3", 3)
                    .when("4", 3)
                    .end();
            apiPlatApply.setCar(carInfo);
        }
        // 芝麻分 1->550以下; 2->550-600; 3->601-650; 4->651-700; 5->700以上;
        if (!ValidParam.isEmpty(apiApplyParameter.getSesameCredit())){
            Integer sesameCredit = ChooseEq.create(apiApplyParameter.getSesameCredit())
                    .when("1", 1)
                    .when("2", 3)
                    .when("3", 4)
                    .when("4", 5)
                    .end();
            apiPlatApply.setSesame(sesameCredit);
        }
        // 花呗额度 1->无花呗; 2->5000以下; 3->5001-10000; 4->10001-20000; 5->20000以上
        if (!ValidParam.isEmpty(apiApplyParameter.getHbLimit())){
            Integer hbLimit = ChooseEq.create(apiApplyParameter.getHbLimit())
                    .when("1", 1)
                    .when("2", 2)
                    .when("3", 3)
                    .when("4", 4)
                    .when("5", 5)
                    .end();
            apiPlatApply.setHuaBei(hbLimit);
        }
        //信用记录 1->信用良好无逾期; 2->近1年内网贷或信用卡逾期少于3次; 3->近1年内网贷或信用卡逾期超过3次
        if (!ValidParam.isEmpty(apiApplyParameter.getOverdue())){
            Integer overdue = ChooseEq.create(apiApplyParameter.getOverdue())
                    .when("1", 1)
                    .when("2", 3)
                    .when("3", 2)
                    .end();
            apiPlatApply.setCreditRecord(overdue);
        }
        // 2. AES ECB加密
        AES aes = AES.createEcb(ENTER_KEY.getBytes());
        String encryptedBase64 = aes.encryptToBase64Str(JsonUtils.toJson(apiPlatApply));
        // 3. 构建Map并序列化
        Map<String, String> responseMap = new HashMap<>();
        responseMap.put("dataContent", encryptedBase64);
        return JsonUtils.toJson(responseMap);

    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        //  撞库返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getString("code"), "0")) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        JSONObject resData = JsonUtils.get(jsonObject.getString("data"));
        JSONArray resProtocolList = resData.getJSONArray("protocolList");
        BigDecimal price = resData.getBigDecimal("price");
        String companyName = resData.getString("companyName");
        String productName = resData.getString("productName");
        String logo = resData.getString("logo");
        String orderId = resData.getString("id");
        List<ApiProtocol> protocolList= CollUtils.newArrayList(newList -> {
            if (ValidParam.isNotEmpty(resProtocolList)) {
                for (int i = 0; i < resProtocolList.size(); i++) {
                    JSONObject protocolObject = resProtocolList.getJSONObject(i);
                    ApiProtocol protocol = new ApiProtocol();
                    protocol.setProtocolName(protocolObject.getString("name"));
                    protocol.setProtocolUrl(protocolObject.getString("url"));
                    newList.add(protocol);
                }
            }
        });

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();

        result.setPrice(price);
        result.setLogoPath(logo);
        result.setDisplayName(companyName);
        result.setProductName(productName);
        result.setApplyId(orderId);
        result.setProtocolList(protocolList);
        return result;
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return null;
    }
}
